/**
 * The Stats
 */

import type { Entity } from '$lib/components';
import { logVisible } from '$lib/render3';
import { Types, defineComponent, type IWorld, type Component, hasComponent, removeEntity } from '$lib/ecs';
import { describe } from '$lib';
import { cleanup } from '$lib/cleanup';

export const HP = defineComponent('HP', {
  maxhp: Types.i32,
  hp: Types.i32,
});

export const Evasion = defineComponent('Evasion', {
  amount: Types.i32,
});

export const Precision = defineComponent('Precision', {
  amount: Types.i32,
});

const corpseDrop = new Map<Component, any>();

export const registerCorpseDrop = ({target, drop}) => {
  corpseDrop.set(target, drop);
};

export const hurt = (world: IWorld, e: Entity, amount: number) => {
  logVisible(e, `${describe(world, e)} is hurt by ${amount}`);
  HP.hp[e] -= amount;
  if (HP.hp[e] <= 0) {
    logVisible(e, `${describe(world, e)} dies`);
    for (let [component, drop] of corpseDrop) {
      if (hasComponent(world, component, e)) {
        drop(world, e);
      }
    }
    const overflow = HP.hp[e];
    cleanup(world, e);
    removeEntity(world, e);
    return amount + overflow;
  }
  return amount;
};
